package com.niubility.controller;

import com.niubility.entity.Article;
import com.niubility.entity.Message;
import com.niubility.entity.SearchMain;
import com.niubility.exception.CustomException;
import com.niubility.server.IArticleServer;
import com.niubility.server.ICheckArticleServer;
import com.niubility.server.ILabService;
import com.niubility.server.IMessageServer;
import com.niubility.server.Impl.*;
import com.niubility.vo.LoadAll;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/*
检查控制类
 */

@RestController
@Transactional
public class CheckArticleController {
    @Resource
    private ICheckArticleServer checkArticleServer;

    @Resource
    private SearchServer searchServer;

    @Resource
    private ILabService labService;

    @Resource
    private IMessageServer messageServer;

    @Resource
    private IArticleServer articleServer;

    private Logger logger = Logger.getLogger(CheckArticleController.class);
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    /*
    * @Author:John
    * @Description: 用于文章检查功能
    * @Date: John 2018/1/26
    * @Params: 传入一个文章对象
    * @Return: 是否存入成功
    *
    */
    @RequestMapping("/CheckArtPass")
    public void CheckPass(HttpServletRequest request, HttpServletResponse response) throws CustomException, UnknownHostException {
        String callback = request.getParameter("callback");
        int artMasterID = Integer.parseInt(request.getParameter("artMaster"));
        String artTitle = request.getParameter("artTitle");
        //String labId = request.getParameter("labId");
        SearchMain searchMain = new SearchMain();
        String result = null;
        boolean delete = false;
        boolean save = false;
        //System.out.println("消息以切入");
        Message message = new Message();
        Article article = null;
        try{
            article = this.checkArticleServer.select(artMasterID,artTitle);
            //在此划分出所属社区
            //System.out.println(article.toString());
            String[] ids = article.getArtLab().split(",");
            int s[] = new int[ids.length];
            for(int i = 0; i < ids.length;i++){
                s[i] = Integer.parseInt(ids[i]);
                //System.out.println(s[i]);
            }
            articleServer.Save(article);
            //System.out.println("文章表添加成功。。。");
            int id = articleServer.SelectByTitle(article);
            //System.out.println("已检索到所需文章。。。");
            searchMain.setId(id);//设置检索表的ID
            searchMain.setMaix(artTitle+" "+article.getArtContext());
            searchServer.InsertInto(searchMain);
            //System.out.println("检索表添加成功。。。");
            save = labService.newArticle(id,s);
            //System.out.println("社区表添加成功。。。");
            //删除检查表中的元组
            delete = checkArticleServer.Delete(artMasterID, artTitle);
            //System.out.println("文章检查表删除成功。。。");
            result = "(" + "{\"returncade\":" + "108}" + ")";
            //向文章表添加新的文章，并获取生成的ID
            int depId = articleServer.SelectByTitle(article);
            //System.out.println("新生文章ID获取成功。。。");
            //向社区表添加新的文章
            String messageForDepPass = "#"+String.valueOf(depId)+"#"+"已通过审核！";
            message.setMesMainid(id);
            message.setMesSendid(000000000);
            message.setMesText(messageForDepPass);
            message.setMesDate(dateFormat.format(new Date()));
            //向消息表填写新的消息
            messageServer.InsertMessage(message);
            //System.out.println("用户消息发送成功。。。");
        }catch (Exception e){
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                logger.debug("数据传输错误."+e);
                throw new CustomException();
            }
            logger.debug("操作失败."+e);
            throw new CustomException();
        }

        //封装为JSONP
        //System.out.println(delete+" "+save);
        int returnCode = delete&save ? 100:108;
        result = callback+"(" + "{\"returncade\":" + returnCode+"}" + ")";
        try{
            response.getWriter().write(result);
        }catch (IOException e){
            logger.debug("IO异常");
        }
   }
    /*
    * @Author:John
    * @Description: 显示所有的数据
    * @Date: John 2018/1/26
    * @Params:
    * @Return: 返回一个json的数据集
    * 测试通过
    */
    @RequestMapping("/CheckActicleLoadAll")
    public void LoadALL(HttpServletResponse response,HttpServletRequest request) throws CustomException {
        //System.out.println("请求已接收！");
        List<Article> list = null;
        response.setCharacterEncoding("utf-8");
        LoadAll articleLoadAll = new LoadAll();
        String callback = request.getParameter("callback");
        int nowPage = Integer.parseInt(request.getParameter("nowPage"));
        int num = Integer.parseInt(request.getParameter("num"));
        //System.out.println(callback+" "+nowPage+" "+num);
        String result = null;
        try{
            list = checkArticleServer.LoadAll(num*(nowPage-1),num);
            //System.out.println(list.toString());
            int pageMore = checkArticleServer.PageNum(num);
            //System.out.println(pageMore);
            if(list !=null && pageMore > 0){
                articleLoadAll.setList(list);
                articleLoadAll.setPageMore(pageMore);
                //System.out.println("数据接收成功");
                result = callback+"("+JSONObject.fromObject(articleLoadAll).toString()+")";
            }else{
                result = callback+"(" + "{\"returncade\":" + "108}" + ")";
            }
        }catch (Exception e){
            logger.debug("显示数据异常."+e);
            result = callback+"(" + "{\"returncade\":" + "108}" + ")";
        }
        try {
            response.getWriter().write(result);
        }catch (IOException e){
            logger.debug("传输异常."+e);
        }
    }
    /*
    * @Author:John
    * @Description: 按照文章的题目和作者的id去查找相应的文章
    * @Date: John 2018/1/26
    * @Params: 一个文章对象
    * @Return: 寻找到的一条元组
    */

    @RequestMapping("/CheckArtSelect")
    public void Select(HttpServletRequest request,HttpServletResponse response) throws CustomException {
        response.setCharacterEncoding("utf-8");
        List<Article> list = null;
        String callback = request.getParameter("callback");
        int id = Integer.parseInt(request.getParameter("artMasterId"));
        String title = request.getParameter("artTitle");
        String result = null;
        //System.out.println(callback+" "+title+" "+id );
        try{
            Article article = checkArticleServer.select(id, title);
            //System.out.println(article);
            if(article != null)
                result = callback+"("+JSONObject.fromObject(article).toString()+")";
            else
                result = callback+"(" + "{\"returncade\":" + "108}" + ")";
        }catch (Exception e){
            result = callback+"(" + "{\"returncade\":" + "108}" + ")";
            logger.debug("传输失败."+e);
            throw new CustomException();
        }
        try{
            response.getWriter().write(result);
        }catch (Exception e){
            logger.debug("查询失败!"+e);
        }
    }
    /*
    * @Author:John
    * @Description: 文章申请的提交将数据存入待审核文章数据库
    * @Date: John 2018/1/26
    * @Params: 一个文章对象
    * @Return: boolean值 表示是否存入
    * 测试通过
    */
    @RequestMapping("/SubmitArt")
    public void Save(HttpServletRequest request,HttpServletResponse response) throws CustomException {
        Article article = new Article();
        String callback = request.getParameter("callback");
        int artMasterId = Integer.parseInt(request.getParameter("artMasterId"));
        String artTitle = request.getParameter("artTitle");
        String artCover = request.getParameter("artCover");
        String artContext = request.getParameter("artContext");
        String labId = request.getParameter("labId");
        String artTestHead = "";
        if(artContext.length()>16) {
            artTestHead = artContext.substring(0, 15);
        }else{
            artTestHead = artContext;
        }
        //System.out.println(callback+" "+artMasterId+" "+artTitle);
        String result = null;
        //设置对象
        article.setArtMasterId(artMasterId);
        article.setArtTitle(artTitle);
        article.setArtCover(artCover);
        article.setArtContext(artContext);
        article.setArtTexthead(artTestHead);
        article.setArtLab(labId);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        article.setArtDate(format.format(new Date()));
        //System.out.println(article.toString());

 //       try {
            boolean bool = checkArticleServer.Save(article);
            //System.out.println(bool);
            if(bool) result = callback+"(" + "{\"returncade\":" + "100}" + ")";
            else result = callback+"(" + "{\"returncade\":" + "108}" + ")";
//        }catch (Exception e){
//            logger.debug("文章提交失败");
//            result = callback+"(" + "{\"returncade\":" + "108}" + ")";
//            //throw new CustomException();
//        }
        try {
            response.getWriter().write(result);
        }catch (IOException e){
            logger.debug("写入失败."+e);
        }
    }
    /*
    * @Author:John
    * @Description:检查未通过删除元组信息
    * @Date: John 2018/1/31
    * @Params:
    * @Return:
    * 测试通过
    */
    @RequestMapping("/CheckArtDelete")
    public void Delete(HttpServletRequest request,HttpServletResponse response){
        String callback = request.getParameter("callback");
        int id = Integer.parseInt(request.getParameter("artMasterId"));
        String title = request.getParameter("artTitle");
        String result = null;
        try {
            //System.out.println(callback+" "+id+" "+title);
            Article article = checkArticleServer.select(id,title);
            boolean bool = checkArticleServer.Delete(id,title);
            if(bool) {
                result = callback+"("+"{\"returncade\":" + "100}"+")";
                Message message = new Message();
                message.setMesSendid(000000000);
                message.setMesMainid(article.getArtMasterId());
                message.setMesText("您的文章"+article.getArtTitle()+"未通过审核！！！");
                messageServer.Save(message);
            }
            else result = callback+"("+"{\"returncade\":" + "108}"+")";
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":" + "108}"+")";
        }
        try{
            response.getWriter().write(result);
        }catch (IOException e){
            logger.debug("传输异常."+e);
        }
    }
}
